package org.jeecg.activiti.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.googlecode.aviator.AviatorEvaluator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.jeecg.activiti.entity.ActKProcessDuplicate;
import org.jeecg.activiti.entity.ActReModelExtend;
import org.jeecg.activiti.entity.ActReModelFormData;
import org.jeecg.activiti.service.IActKProcessDuplicateService;
import org.jeecg.activiti.service.IActReModelExtendService;
import org.jeecg.activiti.service.IActReModelFormDataService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.service.IOnlCgformFieldService;
import org.jeecg.modules.online.cgform.service.IOnlCgformHeadService;
import org.jeecg.modules.online.cgform.util.SqlSymbolUtil;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO 流程抄送管理
 *
 * @author dousw
 * @version 1.0
 * @date 2020/11/24 16:14
 */
@Slf4j
@RestController
@RequestMapping("/activiti/duplicate")
@Api(tags = "流程抄送管理")
public class ActKProcessDuplicateController {

    @Autowired
    private IActKProcessDuplicateService iActKProcessDuplicateService;

    @Autowired
    private ISysUserService iSysUserService;
    
    @Autowired
    private IActReModelFormDataService iActReModelFormDataService;
    
    @Autowired
    private IActReModelExtendService actReModelExtendService;
    
    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;
    
    @Autowired
    private IOnlCgformFieldService fieldService;

    /**
     * 获取我的抄送列表
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取我的抄送列表", notes = "获取我的抄送列表")
    public Result<IPage<ActKProcessDuplicate>> getModelList(ActKProcessDuplicate actKProcessDuplicate,
                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest request){
        Result<IPage<ActKProcessDuplicate>> result = new Result<>();

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        actKProcessDuplicate.setUsername(sysUser.getUsername());

        QueryWrapper<ActKProcessDuplicate> queryWrapper = QueryGenerator.initQueryWrapper(actKProcessDuplicate, request.getParameterMap());
        queryWrapper.orderByDesc("create_time");

        Page<ActKProcessDuplicate> page = new Page<>(pageNo, pageSize);
        IPage<ActKProcessDuplicate> pageList = iActKProcessDuplicateService.page(page, queryWrapper);

        pageList.getRecords().forEach(item ->{
        	ActReModelFormData actReModelFormData = iActReModelFormDataService.getOne(new QueryWrapper<ActReModelFormData>().eq("process_instance_id", item.getProcessInstanceId()));
        	item.setActReModelFormData(actReModelFormData);
        	item.setCreateBy(iSysUserService.getUserByName(item.getCreateBy()).getRealname());
            item.setInitiator(iSysUserService.getUserByName(item.getInitiator()).getRealname());
            item.setTitle(getInstanceName(actReModelFormData));
        });

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    
 // 获取业务标题
    private String getInstanceName(ActReModelFormData actReModelFormData){
    	if(actReModelFormData == null){
    		return "无业务标题";
    	}
    	ActReModelExtend modelExtend = actReModelExtendService.getOne(new QueryWrapper<ActReModelExtend>().eq("model_id", actReModelFormData.getModelId()));
    	Map<String, Object> variables;
        if(actReModelFormData.getTableId() == null){
    		variables = JSONObject.toJavaObject(JSONObject.parseObject(actReModelFormData.getFormData()), Map.class);
        }else{
        	OnlCgformHead head = onlCgformHeadService.getById(actReModelFormData.getTableId());
         	variables = this.fieldService.queryBpmData(actReModelFormData.getTableId(), head.getTableName(), actReModelFormData.getDataId());
         	variables = SqlSymbolUtil.getValueType(variables);
        }
        String expression = modelExtend.getTitle();
        if(org.apache.commons.lang3.StringUtils.isEmpty(expression)){
        	return "无业务标题";
        }
        String title;
        try{
        	title = AviatorEvaluator.execute(expression,variables)+"";
        }catch(Exception e) {
        	log.error("expression========>"+expression);
        	title = "标题加载失败";
        }
        return title;
    }
}
